package tmt.usercenter.web.plugin.datatable;

import com.tmt.annotation.FileValidation;
import com.tmt.datatable.editor.impl.DefaultFileDataHolder;
import com.tmt.helper.ReflectHelper;
import org.springframework.util.StringUtils;
import tmt.usercenter.web.domain.enums.SystemParamCode;
import tmt.usercenter.web.service.SystemParamService;

import java.lang.reflect.Field;

/**
 * 作者：ThreeManTeam
 * 创建时间：2019-03-14 10:24
 */
public class TmtFileDataHolder extends DefaultFileDataHolder {

    protected SystemParamService paramService;

    public TmtFileDataHolder(SystemParamService paramService) {
        this.paramService = paramService;
    }

    @Override
    public void validate(Class<?> clazz, String propName) throws Exception {
        if (this.fileData == null)
            throw new Exception("上传文件不能为null");

        Field field = ReflectHelper.findFieldByName(clazz, propName);
        FileValidation validation = field.getAnnotation(FileValidation.class);
        if (validation != null) {
            int maxLen = validation.maxSize();
            try {
                if (!StringUtils.isEmpty(validation.configParamName())) {
                    maxLen = paramService.getSystemParamValue(SystemParamCode.valueOf(validation.configParamName()), int.class);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            if (this.fileData.getSize() > maxLen)
                throw new Exception(String.format("上传文件的大小不能超过%sK", maxLen / 1024));
        }
    }

}
